#pragma once

#include "Util.hpp"
#include <vector>
#include <cassert>
namespace log
{
    class Buffer
    {
#define DEFAULT_BUFFER_SIZE 10 * 1024 * 1024
#define THRESHOLD_BUFFER_SIZE 80 * 1024 * 1024
#define INCREMENT_BUFFER_SIZE 10 * 1024 * 1024
    public:
        Buffer() : _buffer(DEFAULT_BUFFER_SIZE), _Writer_idx(0), _Readr_idx(0)
        {
        }
        // 向缓冲区写入数据
        void Push(const char *data, size_t len)
        {
            // 先判断空间是否足够,1:不够扩容 2:阻塞
            // if((_buffer.size()-_Writer_idx)<len) return;  //直接返回

            EnsureEnoughSize(len);
            // 向缓冲区中写入指定的数据
            std::copy(data, data + len, &_buffer[_Writer_idx]);
            MoveWriter(len);
        }
        // 移动读写指针的接口
        void MoveWriter(size_t len)
        {
            assert((_Writer_idx + len) <= _buffer.size());
            _Writer_idx += len;
        }
        void MoveReader(size_t len)
        {
            assert(ReadAbleSize() >= len);
            _Readr_idx += len;
        }
        // 获取可读数据起始地址
        const char *Begin()
        {
            return &_buffer[_Readr_idx];
        }
        // 获取可读数据长度的接口
        size_t ReadAbleSize()
        {
            return (_Writer_idx - _Readr_idx);
        }
         size_t WriteAbleSize()
        {
            return (_buffer.size() - _Writer_idx);
        }
        void reset()
        {
            _Writer_idx = _Readr_idx = 0;
        }
        void Swap(Buffer &buffer)
        {
            _buffer.swap(buffer._buffer);
            std::swap(_Writer_idx, buffer._Writer_idx);
            std::swap(_Readr_idx, buffer._Readr_idx);
        }

        bool empty()
        {
            return _Writer_idx == _Readr_idx;
        }

    private:
        // 小于阈值空间成倍增加,大于阈值空间线性增加
        void EnsureEnoughSize(size_t len)
        {
            // 空间足够
            if ((_buffer.size() - _Writer_idx) >= len)
                return;
            // 空间不够
            size_t newsize = 0;
            if (_buffer.size() < THRESHOLD_BUFFER_SIZE)
                newsize = _buffer.size() * 2 + len;
            else
                newsize = _buffer.size() + INCREMENT_BUFFER_SIZE + len;
            _buffer.resize(newsize);
        }

    private:
        std::vector<char> _buffer;
        size_t _Writer_idx;
        size_t _Readr_idx;
    };
}